import Vue from 'vue'
import { getUserInfo, getUserSceneMenuInfo, logout, login, mobileLogin } from '@/api/user'
import { ACCESS_TOKEN, TENANT_NO, USER_INFO, EXPIRES_IN, REFRESH_TOKEN, USERISFIRSTLOGIN } from '@/store/mutation-types'
import { encryption, compare, randomString, generateChildRouters } from '@/utils/util'
import md5 from 'md5'
import { Modal } from 'ant-design-vue'
import store from '@/store'
import router from '@/router'
const father = {
  state: {
    permissionList: [],
    uniqueInfo: {}
  },
  mutations: {
    'SET_PERMISSIONLIST' (state, permissionList) {
      state.permissionList = permissionList
    },
    SET_UNIQUE_INFO: (state, uniqueInfo) => {
      state.uniqueInfo = uniqueInfo
    }
  },
  actions: {
    GetUserInfoList () {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then(res => {
            const { userPermissionList, userPermissionTree, userRoleList } = res.data
            Vue.ls.set('userPermissionList', userPermissionList)
            Vue.ls.set('userPermissionTree', userPermissionTree)
            Vue.ls.set('userRoleList', userRoleList)
            let useInfo = {
              userNo: res.data.userNo,
              userName: res.data.userName,
              remark: res.data.remark,
              mobile: res.data.mobile,
              tenantNo: res.data.tenantNo,
              userType: res.data.userType,
              isManager: res.data.isManager
            }
            Vue.ls.set(USER_INFO, useInfo)
            resolve(res.data)
          })
          .catch(err => {
            Vue.ls.remove(ACCESS_TOKEN)
            reject(err)
          })
      })
    },

    GetPermissionList ({ commit }) {
      return new Promise((resolve, reject) => {
        getUserSceneMenuInfo()
          .then(res => {
            if (res.code !== 0) {
              Modal.error({
                title: '温馨提示',
                content: res.msg,
                okText: '关闭',
                mask: false,
                onOk: () => {
                  store.dispatch('Logout')
                }
              })
              return false
            }
            let useInfo = {
              userNo: res.data.userNo,
              userName: res.data.userName,
              remark: res.data.remark,
              mobile: res.data.mobile,
              tenantNo: res.data.tenantNo,
              userType: res.data.userType,
              isManager: res.data.isManager
            }
            Vue.ls.set(USER_INFO, useInfo)
            if (Vue.ls.get(USER_INFO).userType === '1') {
              const precessEnv = process.env
              let dispatchUrl = ''
              if (precessEnv.VUE_APP_FLAG === 'dev' || precessEnv.VUE_APP_FLAG === 'local') {
                dispatchUrl = 'http://10.9.101.19:6005/031-002/#/'
              } else {
                dispatchUrl = 'http://10.9.102.68:6005/031-102/#/'
              }
              let userMenuList = [
                {
                  permissionInfoList: [],
                  id: 1,
                  sceneNo: 'SCE1605583742101',
                  sceneName: '用户中心',
                  menuName: '用户中心',
                  dispatchUrl: dispatchUrl,
                  menuOrder: 2,
                  remark: '',
                  picUrl: 'icon-shexiangtou',
                  createdUser: 'USER1600234997501',
                  gmtCreated: '2020-11-17T17:38:48',
                  updatedUser: 'USER1600234997501',
                  gmtUpdated: '2020-12-02T16:26:28',
                  menuRoute: '/ucenter'
                }
              ]
              let menuData = [
                {
                  path: '/ucenter',
                  name: 'ucenter',
                  component: 'layouts/PageLayout',
                  route: 1,
                  meta: {
                    url: dispatchUrl,
                    icon: 'tool',
                    title: '用户中心'
                  }
                }
              ]
              Vue.ls.set('userMenuList', userMenuList)
              commit('SET_PERMISSIONLIST', menuData)
              resolve(menuData)
            } else {
              let newMenu = []
              const newData = res.data.sceneTreeResps.sort(compare('menuOrder'))
              // newData.map(obj => {
              //   let o = {
              //     children: obj.children,
              //     path: obj.menuRoute,
              //     component: 'children' + obj.menuRoute + '/index',
              //     name: obj.menuRoute,
              //     // component: 'layouts/PageLayout',
              //     route: 1,
              //     sceneNo: obj.sceneNo,
              //     meta: {
              //       url: obj.dispatchUrl,
              //       icon: obj.picUrl,
              //       title: obj.sceneName
              //     }
              //   }
              //   newMenu.push(o)
              // })
              newMenu = generateChildRouters(newData)
              commit('SET_PERMISSIONLIST', newMenu)
              resolve(newData)
            }
          })
          .catch(err => reject(err))
      })
    },
    // 登录超时直接登出
    LogoutOut ({ commit }) {
      commit('SET_PERMISSIONLIST', [])
      Vue.ls.remove(ACCESS_TOKEN)
      Vue.ls.remove(TENANT_NO)
      Vue.ls.remove(EXPIRES_IN)
      Vue.ls.remove(REFRESH_TOKEN)
      Vue.ls.remove(USER_INFO)
      router.push({ path: '/user/login' })
    },
    // 登出
    Logout ({ commit }) {
      return new Promise(resolve => {
        logout()
          .then(() => {
            resolve()
            commit('SET_PERMISSIONLIST', [])
            Vue.ls.remove(ACCESS_TOKEN)
            Vue.ls.remove(TENANT_NO)
            Vue.ls.remove(EXPIRES_IN)
            Vue.ls.remove(REFRESH_TOKEN)
            Vue.ls.remove(USER_INFO)
            router.push({ path: '/user/login' })
            // window.location.reload()
          })
          .catch(() => {
            resolve()
          })
      })
    },
    // 登录
    // eslint-disable-next-line no-unused-vars
    Login ({ commit }, userInfo) {
      // const user = encryption({ data: userInfo, key: 'pigxpigxpigxpigx', param: ['password'] })
      userInfo.password = randomString(3) + md5(userInfo.password) + randomString(3)
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(res => {
            console.log(res.tenantNo)
            Vue.ls.set(ACCESS_TOKEN, res.data, 24 * 60 * 60 * 1000)
            Vue.ls.set(TENANT_NO, res.tenantNo, 24 * 60 * 60 * 1000)
            Vue.ls.set(EXPIRES_IN, res.expires_in, 24 * 60 * 60 * 1000)
            Vue.ls.set(REFRESH_TOKEN, res.refresh_token, 24 * 60 * 60 * 1000)
            Vue.ls.set(
              USER_INFO,
              {
                user_id: res.user_id,
                username: res.username,
                relname: res.relname,
                role_type: res.role_type,
                org_code: res.org_code,
                dept_id: res.dept_id,
                tag: res.tag,
                phone: res.phone
              },
              24 * 60 * 60 * 1000
            )
            let isFirstLogin = localStorage.getItem(USERISFIRSTLOGIN)
            if (isFirstLogin === null) {
              Vue.ls.set(USERISFIRSTLOGIN, true)
            }
            resolve(res)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 预发布环境和生产环境登录
    // eslint-disable-next-line no-unused-vars
    mobileLogin ({ commit }, userInfo) {
      const user = encryption({ data: userInfo, key: 'pigxpigxpigxpigx', param: ['password'] })
      return new Promise((resolve, reject) => {
        mobileLogin(user.username, user.password, user.code, user.randomStr)
          .then(res => {
            Vue.ls.set(ACCESS_TOKEN, res.access_token, 24 * 60 * 60 * 1000)
            Vue.ls.set(EXPIRES_IN, res.expires_in, 24 * 60 * 60 * 1000)
            Vue.ls.set(REFRESH_TOKEN, res.refresh_token, 24 * 60 * 60 * 1000)
            Vue.ls.set(
              USER_INFO,
              {
                user_id: res.user_id,
                username: res.username,
                relname: res.relname,
                role_type: res.role_type,
                org_code: res.org_code,
                dept_id: res.dept_id,
                tag: res.tag,
                phone: res.phone
              },
              24 * 60 * 60 * 1000
            )
            let isFirstLogin = localStorage.getItem(USERISFIRSTLOGIN)
            if (isFirstLogin === null) {
              Vue.ls.set(USERISFIRSTLOGIN, true)
            }
            resolve(res)
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  }
}

export default father
